// 引入模块依赖
const fs = require('fs'); //node的文件系统模块
const path = require('path');
const jwt = require('jsonwebtoken'); //引入 token 模块

//创建 token 类
class Jwt {
  constructor(data) {
    this.data = data;
  }

  //生成 token
  generateToken() {
    let data = this.data;
    let created = Math.floor(Date.now() / 1000);
    //生成私钥
    //__dirname --- 当前文件的路径
    //'../pem/private_key.pem' --- 要进入的文件的相对路径
    let cert = fs.readFileSync(path.join(__dirname,'../pem/private_key.pem'));  //cert --- private_key
    let token = jwt.sign({
      data,
      exp: created + 30 * 60, //设置 token 过期时间， 30分钟后， 秒为单位
    },cert)   //cert --- 作为唯一的标识，标识这段 token
    return token;
  }

  //校验 token
  verifyToken() {
    let token = this.data;
    //公钥
    let cert = fs.readFileSync(path.join(__dirname,'../pem/public_key.pem'));  //cert --- private_key
    let res;
    try {
      let result = jwt.verify(token, cert) || {};
      // 默认值给0 ---解构赋值
      let {exp = 0} = result, current = Math.floor(Date.now() / 1000);
      if (current <= exp) {
        res = result.data || {};
      }
    } catch {
      res = 'err'
    }
    return res;
  }
}

module.exports = Jwt;